import sys
import json
import re

from config import getConfigParams
from requestUrl import getDocByUrl,getEntryIdByUrl
from formatContent import formatContent
from logs import saveLog

# 获取配置参数
configParams = getConfigParams(sys.argv)
url = configParams['real_url']
env = configParams['env']

# 获取文章ID
entryId = getEntryIdByUrl(configParams['base_url'])

# 获取html文本doc，得到pq对象
doc = getDocByUrl(url)

# 把p标签下，所有图片的_src替换成src，并移除_src属性
for p in doc('img'):
    doc(doc(p)('img')).attr('src', doc(doc(p)('img')).attr('_src'))
    doc(doc(p)('img')).removeAttr('_src')

# 封面图，doc中的第一张图就是封面图
coverUrl = doc('.top-img img').attr('src')
if (coverUrl == None):
    coverUrl = re.findall("<meta.*?property=\"og:image\" content=\"([^\"]+)\"/>", doc.html())[0]

# 标题
title = doc('.article__title').text()

# 文章正文
articleContent = doc('.article__content').html()

# 文章作者
authorName = doc('.author-info__username').text()

# 时间
publicTime = doc('.article__time').text()

# 去【李世泉】那里过滤标签
content = formatContent(articleContent, env=env)

result = {
    'entry_id': entryId,
    'not_format_content': articleContent,
    'content': content,
    'author_name': authorName,
    'cover_url': coverUrl,
    'public_time': 0,
    'description': '',
    'title': title,
}
logData = {
    'params': sys.argv,
    'result': result
}
saveLog(json.dumps(logData, ensure_ascii=False))
print(json.dumps(result, ensure_ascii=False))
